# -*- coding:utf-8 -*-

import pymysql
import pymysql.cursors


class Connection(object):
    mysql_config = {
        "driver": "default",
        "default": {
            "host": "47.108.114.144",  # 连接主机的ip
            "port": 3306,  # 连接主机的端口
            "user": "fcl",  # 本地数据库的用户名
            "password": "fcl@123456",  # 本地数据库的密码
            "database": "novel",  # 连接的数据库
            "charset": "utf8",  # 设置编码格式
            "cursorclass": pymysql.cursors.DictCursor,
        },
        ## 暂时不做长连接
        "long_connect": False,
    }

    _instance = None

    """ def __new__(cls, *args, **kwargs):
        if not isinstance(cls._instance, cls):
            cls._instance = super(Connection, cls).__new__(cls, *args, **kwargs)
            cls._instance.connection()
        return cls._instance """

    _conn = None
    _cursor = None

    def __init__(self) -> None:
        if self._conn:
            return
        print("refresh init", self._conn)
        self.connection()

    def connection(self):
        try:
            driver = self.mysql_config.get("driver", "default")
            config = self.mysql_config.get(driver, None)
            if not config:
                raise Exception("未找到数据库连接配置!")
            print(config)
            self._conn = pymysql.connect(**config)  # 连接数据库，配置参数
            self._cursor = self._conn.cursor()  # 创建一个游标，用来执行查询
        except Exception as e:
            # raise Exception(f"数据库连接失败！！！\n请检查表名、配置参数是否正确或检查本地数据库是否已启动！\n{e}")
            pass

    def get_connection(self):
        try:
            self._conn.ping()
        except Exception as e:
            print("重新链接1", self._cursor)
            self.connection()
            print(e)
        return self._conn

    def get_cursor(self):
        try:
            # print("游标", self._cursor)
            self._conn.ping()
        except Exception as e:
            print("重新链接2", self._cursor)
            self.connection();
        return self._cursor

    def refres_cursor(self):
        try:
            self._conn.ping()
        except Exception as e:
            self.connection()
        self._cursor = self._conn.cursor()
        return self._cursor

    def close(self):
        if self._cursor is None:
            return True
        self._cursor.close()
        self._conn.close()
        self._conn = None
        self._cursor = None
        return True
